﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BF_160
{
    public partial class FrmComSelect : Form
    {
        Ini cIni;
        string strAppDir;

        public FrmComSelect()
        {
            InitializeComponent();

            strAppDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
            cIni = new Ini(strAppDir + "\\config.ini");

            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void FrmComSelect_Load(object sender, EventArgs e)
        {

            String[] Portname = SerialPort.GetPortNames();
            string selectCOM = cIni.ReadValue("COM", "Select","COM1");

            if(Portname.Length > 0)
            {
                foreach (var item in Portname)
                {
                    comboBox1.Items.Add(item);
                }
                if (Portname.Contains(selectCOM))
                {
                    comboBox1.SelectedItem = selectCOM;
                }
                else
                {
                    comboBox1.SelectedIndex = 0;
                }
            }
            else
            {
                MessageBox.Show("没有发现可用串口!");
            }
            open_com1();
        }

        private void open_com1()
        {

            try
            {
                SerialPort serialPort = new SerialPort(comboBox1.SelectedItem.ToString());
                serialPort.Open();

                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                    serialPort.PortName = comboBox1.SelectedItem.ToString();
                    serialPort.BaudRate = 9600;
                }
                cIni.Write("COM", "Select", comboBox1.SelectedItem.ToString());

            }
            catch (Exception ee)
            {
                MessageBox.Show("端口打开失败,请重新选择端口!\n" + ee.Message);
                return;
            }
            FrmYT frmYT;
            FrmYDL frmYDL;
            if (MyGlobal.FristShow == 1)
            {
                frmYT = new FrmYT();
                this.Close();
                frmYT.Show();
            }
            else if (MyGlobal.FristShow == 2)
            {
                frmYDL = new FrmYDL();
                frmYDL.Show();
                //this.Close();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            open_com1();
        }
    }
}
